package com.learning.grpc.service;

import com.alibaba.fastjson.JSONObject;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class LearningServiceImpl extends LearningServiceGrpc.LearningServiceImplBase {

    private Server server;

    @Override
    public void getService(RequestService request, StreamObserver<ResponseService> responseObserver) {
        log.info("clientId:{},clientData:{}", request.getClientId(), JSONObject.toJSONString(request.getClientDataMap()));
        ResponseService responseService = ResponseService.newBuilder().setServiceId(true).setClientCount(10).build();
        responseObserver.onNext(responseService);
        responseObserver.onCompleted();
    }

    @Override
    public void saveService(ServiceInfo request, StreamObserver<ResponseService> responseObserver) {
        log.info("ip:{},port:{}", request.getIp(), request.getPort());
        ResponseService responseService = ResponseService.newBuilder().setServiceId(true).setClientCount(1).build();
        responseObserver.onNext(responseService);
        responseObserver.onCompleted();
    }

    private void stop() {
        if(null != server) {
            server.shutdown();
        }
    }

    private void blockUnitlShutdown() throws InterruptedException {
        if(server != null) {
            server.awaitTermination();
        }
    }

    private void start() throws IOException {
        server = ServerBuilder.forPort(8080).addService(new LearningServiceImpl()).build().start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                LearningServiceImpl.this.stop();
                log.info("关闭服务");
            }
        });
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        LearningServiceImpl learningService = new LearningServiceImpl();
        learningService.start();
        learningService.blockUnitlShutdown();
    }
}